import React, { useEffect, CSSProperties } from "react";
import {
  Breadcrumbs as Bcs,
  Link,
  LinkOwnProps,
  Typography,
} from "@mui/material";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import s from "./index.module.scss";

export interface IBreadcrumbsItem {
  name: string;
  value?: string;
  color?: LinkOwnProps["color"];
  id?: string;
  /**
   * route path
   */
  path?: string;
}
export interface BreadcrumbsProps {
  /**
   * IBreadcrumbsItem[]|string[]
   */
  list: IBreadcrumbsItem[] | string[];
  /**
   * clickCb
   */
  itemClick?: (data: IBreadcrumbsItem) => void;
  /**
   * LinkOwnProps["underline"]
   */
  underline?: "none" | "hover" | "always";
  /**
   * config lastItem click
   */
  lastItemClick?: boolean;
  /**
   * extra styleObj CSSProperties
   */
  style?: CSSProperties;
}

/**
 * Breadcrumbs
 */
const Breadcrumbs: React.FC<BreadcrumbsProps> = (props) => {
  const {
    list = [],
    itemClick,
    underline = "none",
    lastItemClick = false,
    style = {},
  } = props;
  const len = list.length;
  const listNode = list.map((value: unknown, k: number) => {
    let v: IBreadcrumbsItem;
    if (typeof value === "string") {
      v = {
        name: value,
      } as IBreadcrumbsItem;
    } else {
      v = value as IBreadcrumbsItem;
    }
    const key = v?.id || String(k);
    const { color = "#212529" } = v;
    if (k === len - 1) {
      return (
        <Typography
          style={{
            cursor: lastItemClick && itemClick ? "pointer" : "inherit",
          }}
          key={key}
          color={color}
          fontWeight="bold"
          onClick={() => {
            lastItemClick && itemClick && itemClick(v);
          }}
        >
          {v.name}
        </Typography>
      );
    } else {
      return (
        <Link
          style={{
            cursor: itemClick ? "pointer" : "inherit",
          }}
          underline={underline}
          key={key}
          color={color}
          onClick={() => {
            itemClick && itemClick(v);
          }}
        >
          {v.name}
        </Link>
      );
    }
  });
  useEffect(() => {
    return () => {};
  }, []);

  return (
    <div className={s.breadcrumbs} style={style}>
      <Bcs
        separator={<NavigateNextIcon fontSize="small" />}
        aria-label="breadcrumb"
      >
        {listNode}
      </Bcs>
    </div>
  );
};

export default Breadcrumbs;
